package xin.lhuo.we.server.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.lhuo.we.server.entity.User;
import xin.lhuo.we.server.enums.ResultEnum;
import xin.lhuo.we.server.exception.WeException;
import xin.lhuo.we.server.form.UserForm;
import xin.lhuo.we.server.dao.UserMapper;
import xin.lhuo.we.server.service.IUserService;

import java.util.UUID;

/**
 * @author Lhuo
 * @date 2019/4/30 16:01
 */
@Service("userServer")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveUser(UserForm userForm) {
        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        user.setRole(1);
        if (userMapper.checkUsername(user.getUsername()) != 0) {
            throw new WeException(ResultEnum.PARAM_ERROR.getCode(), "用户名已存在");
        }
        if (userMapper.checkPhone(user.getPhone()) != 0) {
            throw new WeException(ResultEnum.PARAM_ERROR.getCode(), "手机号已存在");
        }
        userMapper.save(user);
    }

    @Override
    public User login(String username, String password) {
        if (userMapper.checkUsername(username) == 0) {
            throw new WeException(ResultEnum.PARAM_ERROR.getCode(), "用户不存在");
        }

        User user = userMapper.selectByUsernameAndPassword(username, password);
        if (user == null) {
            throw new WeException(ResultEnum.PARAM_ERROR.getCode(), "密码错误");
        }
        String token = UUID.randomUUID().toString();
        user.setToken(token);
        user.setCreateTime(null);
        user.setUpdateTime(null);
        user.setPassword(null);
        return user;
    }
}
